<template>
	<view class="sunui-add-list">
		<view class="sunui-add-list-items" :style="{
				height: size[0],
				width: size[1]
			}" v-for="(item, index) in imgLists" :key="index">
			<image :src="item.url" :data-imgurl="item.url" @tap="showImgs" class="sunui-add-list-img" :mode="imgMode">
			</image>
			<view class="sunui-add-list-remove sunui-icons icon-close" :style="{ color: closeBtnColor }"
				@tap.stop="removeImg" :id="'sunui-items-img-' + index">×</view>
			<view class="upload-progress" :style="{ width: size[1] }">
				<progress :percent="item.progress" :stroke-width="progressSize" :activeColor="progressColor"
					:backgroundColor="progressBGColor" />
			</view>
			<!-- 失败 -->
			<view class="sunui-add-list-reup" @tap.stop="retry" :data-index="index" v-if="item.error">
				<text class="sunui-add-list-reup-icon sunui-icons icon-retry"></text>
				<text class="sunui-add-list-reup-text">失败重试</text>
			</view>
		</view>
		<view class="sunui-add-list-items sunui-add-list-btn" :style="{
				height: size[0],
				width: size[1],
				backgroundColor: backgroundColor,
				border: border,
				backgroundImage: backgroundImage==''? '':backgroundImage=='nationalEmblem'?'url('+nationalEmblem()+')':'url('+facade()+')',
			}" @tap="addImg" v-if="imgLists.length < maxFileNumber">
			<!-- <view class="sunui-add-list-btn-icon">+</view> -->
			<slot name="icon"></slot>
			<view class="sunui-add-list-btn-text">{{ btnName }}</view>
		</view>
	</view>
</template>
<script>
	export default {
		props: {
			maxFileNumber: {
				type: Number,
				default: 9
			},
			btnName: {
				type: String,
				default: '添加照片'
			},
			border: {
				type: String,
				default: 'none'
			},
			// 背景颜色
			backgroundColor: {
				type: String,
				default: 'transparent'
			},
			items: {
				type: Array,
				default: function() {
					return [];
				}
			},
			backgroundImage: {
				type: String,
				default: ''
			},
			closeBtnColor: {
				type: String,
				default: '#666666'
			},
			uploadServerUrl: {
				type: String,
				default: ''
			},
			progressSize: {
				type: Number,
				default: 1
			},
			progressColor: {
				type: String,
				default: '#27BD81'
			},
			progressBGColor: {
				type: String,
				default: '#F8F8F8'
			},
			fileName: {
				type: String,
				default: 'img'
			},
			formData: {
				type: Object,
				default: function() {
					return {};
				}
			},
			imgMode: {
				type: String,
				default: 'widthFix'
			},
			header: {
				type: Object,
				default: function() {
					return {};
				}
			},

			// storageMode:2是‘阿里云’上传，3是‘七牛云’ 上传
			storageMode: {
				type: String,
				default: ''
			},

			// 图片大小
			size: {
				type: Array,
				default: () => ['222rpx', '222rpx']
			}
		},
		data() {
			return {
				imgLists: [],
				updatting: false,
				lastUpdata: false
			};
		},
		watch: {
			imgLists(newVal, oldVal) {
				if (!this.updatting) {
					this.$emit('change', newVal);
				}
			}
		},
		computed: {
			// nationalEmblem() {
			// 	return () => {
			// 		return require('../../static/Group 3108.png')
			// 	}
			// },
			// facade() {
			// 	return (item) => {
			// 		return require(`../../static/Group 3148.png`)
			// 	}
			// }
		},
		methods: {
			clearAllImgs() {
				this.imgLists = [];
			},
			addImg() {
				var num = this.maxFileNumber - this.imgLists.length;
				if (num < 1) {
					return false;
				}
				//uni.showLoading({title:""});
				uni.chooseImage({
					count: num,
					sizeType: ['compressed'],
					success: res => {
						for (let i = 0; i < res.tempFilePaths.length; i++) {
							this.imgLists.push({
								url: res.tempFilePaths[i],
								progress: 0,
								error: false
							});
						}

						//uni.hideLoading();
					},
					complete: function() {
						//uni.hideLoading();
					},
					fail: function() {
						//uni.hideLoading();
					}
				});
			},
			removeImg(e) {
				var index = e.currentTarget.id.replace('sunui-items-img-', '');
				var removeImg = this.imgLists.splice(index, 1);
				this.$emit('removeImg', removeImg[0]);
			},
			showImgs(e) {
				var currentImg = e.currentTarget.dataset.imgurl;
				var imgs = [];
				for (let i = 0; i < this.imgLists.length; i++) {
					imgs.push(this.imgLists[i].url);
				}
				uni.previewImage({
					urls: imgs,
					current: currentImg
				});
			},
			upload(index) {

				if (this.updatting) {
					return;
				}
				this.updatting = true;
				if (!index) {
					index = 0;
				}
				uni.showLoading({
					title: '图片上传中'
				});
				this.uploadBase(index);

			},
			retry(e) {
				var index = e.currentTarget.dataset.index;
				this.upload(index);
			},
			uploadBase(index) {

				// 全部上传完成
				console.log(this.imgLists, index)
				if (!this.storageMode == 2) {
					if (this.imgLists.length !== 1) {
						if (index >= this.imgLists.length - 1) {
							if (this.lastUpdata == false) {
								uni.hideLoading();
								this.updatting = false;

								console.log('全部王超1')

								this.$nextTick(() => {
									this.$emit('uploaded', this.imgLists);
								})
								return;
							}
						}
					} else {
						if (index >= this.imgLists.length) {
							if (this.lastUpdata == false) {
								uni.hideLoading();
								this.updatting = false;

								console.log('全部王超2')

								this.$nextTick(() => {
									this.$emit('uploaded', this.imgLists);
								})
								return;
							}
						}
					}
				} else {
					if (index > this.imgLists.length - 1) {

						uni.hideLoading();
						this.updatting = false;

						console.log('全部王超3')

						this.$nextTick(() => {
							this.$emit('uploaded', this.imgLists);
						})
						return;

					}
				}


				// 验证后端
				if (this.uploadServerUrl == '') {
					uni.showToast({
						title: '请设置上传服务器地址',
						icon: 'none'
					});
					return;
				}
				// 检查是否是默认值
				if(this.imgLists[index]?.progress){
					if (this.imgLists[index].progress >= 1) {
						console.log('检查是否是默认值')
						this.uploadBase(index + 1);
						return;
					}
				}
				console.log('22123')
				// this.imgLists[index].error = false;

				// 创建上传对象
				console.log(this.formData)
				const task = uni.uploadFile({
					url: this.uploadServerUrl,
					filePath: this.imgLists[index].url,
					name: 'file' || this.fileName,
					formData: this.formData,
					header: this.header,
					success: uploadRes => {
						console.log('uploadRes-------------', uploadRes, 'this.formData', this.formData,
							'this.uploadServerUrl', this.uploadServerUrl);
						/* 阿里云上传 */


						/* 七牛云上传 */
						uploadRes = JSON.parse(uploadRes.data);
						console.log('uploadRes', this.imgLists)
						if (uploadRes.code != 0) {
							// console.log('进入失败uploadRes', uploadRes);
							uni.showToast({
								title: '上传失败 : ' + uploadRes.data,
								icon: 'none'
							});
							this.error(index);
						} else {
							// console.log('进入成功uploadRes', uploadRes);
							//上传图片成功
							this.imgLists[index].progress = 100;
							this.imgLists[index].url = uploadRes.data.url;
							this.imgLists[index].result = uploadRes;
							console.log('imgLists', this.imgLists)
							this.uploadBase(index + 1);
						}

					},
					fail: e => {
						uni.showToast({
							title: '上传失败，请点击图片重试',
							icon: 'none'
						});
						this.error(index);
					}
				});
				task.onProgressUpdate(res => {
					if (res.progress > 0) {
						this.imgLists[index].progress = res.progress;
						this.imgLists.splice(index, 1, this.imgLists[index]);
					}
				});
			},
			// 上传错误
			error(index) {
				this.updatting = false;
				setTimeout(() => {
					this.imgLists[index].progress = 0;
					this.imgLists[index].error = true;
					this.$emit('uploaderror');
				}, 500);
			},
			// 设置默认值
			setItems(items) {
				this.imgLists = [];
				for (let i = 0; i < items.length; i++) {
					this.imgLists.push({
						url: items[i],
						progress: 100
					});
				}
			}
		}
	};
</script>
<style scoped>
	.sunui-add-list {
		display: flex;
		flex-wrap: wrap;
	}

	.sunui-add-list-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.sunui-add-list-btn-text {
		font-size: 26rpx;
		line-height: 36rpx;
		text-align: center;
		color: #999999;
		width: 100%;
	}

	.sunui-add-list-btn-icon {
		font-size: 80rpx;
		height: 80rpx;
		line-height: 80rpx;
		margin-bottom: 20rpx;
		color: #999999;
	}

	.sunui-add-list-items {
		width: 222rpx;
		height: 222rpx;
		overflow: hidden;
		margin-top: 10rpx;
		margin-right: 11rpx;
		border: 1px dashed #bfbfbf;
		background: #fff;
		font-size: 0;
		position: relative;
		border-radius: 10rpx;
	}

	.sunui-add-list-image {
		width: 222rpx;
	}

	.sunui-add-list-remove {
		line-height: 50rpx;
		text-align: center;
		font-size: 40rpx;
		position: absolute;
		z-index: 999;
		width: 60rpx;
		height: 60rpx;
		right: 10rpx;
		top: 10rpx;
		color: #888888;
	}

	/* .sunui-add-list-remove {
	width: 50rpx;
	height: 50rpx;
	line-height: 50rpx;
	text-align: center;
	font-size: 40rpx;
	position: absolute;
	z-index: 5;
	right: 10rpx;
	top: 10rpx;
	color: #888888;
} */
	.upload-progress {
		position: absolute;
		z-index: 2;
		left: 0;
		bottom: 10rpx;
		width: 180rpx;
		padding: 0 21rpx;
	}

	.sunui-add-list-reup {
		position: absolute;
		z-index: 3;
		left: 0;
		top: 0rpx;
		width: 222rpx;
		height: 222rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: rgba(0, 0, 0, 0.3);
		flex-direction: column;
	}

	.sunui-add-list-reup-icon {
		text-align: center;
		width: 100%;
		color: #ffffff;
		display: block;
		font-size: 80rpx;
		line-height: 100rpx;
	}

	.sunui-add-list-reup-text {
		text-align: center;
		width: 100%;
		color: #ffffff;
		display: block;
		font-size: 20rpx;
		line-height: 30rpx;
	}

	.sunui-add-list-img {
		width: 100%;
	}
</style>